﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Google.GData.YouTube;
using Google.GData.Client;
using FlickrNet;
using Resources;
using Google.GData.Photos;
using System.Xml;
using System.Net;
using System.IO;
using LinqToTwitter;

public partial class Controls_WebContent : System.Web.UI.UserControl
{
    public string SearchPhrase { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {

            try
            {
                //show news from google        
                GoogleNewsDataSource.DataFile = string.Format(GoogleHelper.GoogleNewsFeedUrl, SearchPhrase);
                GoogleNewsListView.DataSourceID = GoogleNewsDataSource.UniqueID;
                GoogleNewsListView.DataBind();

            }
            catch (Exception)
            {



            }
            


            //show news from live com
            try
            {
                LiveNewsDataSource.DataFile = string.Format(LiveHelper.LiveNewsFeedUrl, SearchPhrase);
                LiveNewsListView.DataSourceID = LiveNewsDataSource.UniqueID;
                LiveNewsListView.DataBind();
            }
            catch (Exception)
            {

                //todo;
            }


            //search results from live.com
            try
            {
                LiveSearchDataSource.DataFile = string.Format(LiveHelper.LiveSearchFeedUrl, SearchPhrase);
                LiveSearchListView.DataSourceID = LiveSearchDataSource.UniqueID;
                LiveSearchListView.DataBind();
            }
            catch (Exception)
            {

                //todo
            }



            try
            {
                LoadVideos(this.SearchPhrase);


            }
            catch (Exception)
            {


            }
            SetTheCorrectTabIndex();
            if (VideosListView.Items.Count > 0)
            {
                VideosListView.SelectedIndex = 0;
                VideosListView_SelectedIndexChanged(VideosListView, new EventArgs());
            }

            LoadTweets();



        }
    }

    void BlogSearchDataSource_DataBinding(object sender, EventArgs e)
    {
        
    }

    private void LoadTweets()
    {
        SingleUserAuthorizer singleUserAuthorizer = new SingleUserAuthorizer()
        {
            Credentials = new InMemoryCredentials()
            {
                ConsumerKey = "ygwNi31knXGelK47zfKsA",
                ConsumerSecret = "DA9oYMqZHXIpBH567TLj1Fm8LXnFCrROVRx7EdVqk",
                OAuthToken = "87395666-Mqq3Kn6UtbFsSfxpl98PDI8TLt7WjT9pKLLaP7koe",

                AccessToken = "vIQIjOInIEAAjABkEGsAzBwIyrz56ASNo50ObL1cceU"
            }
        };



        using (var twitterContext = new TwitterContext(singleUserAuthorizer))
        {
            var queryResults =
                from search in twitterContext.Search
                where search.Type == SearchType.Search &&
                      search.Query == this.SearchPhrase
                select search;

            foreach (var search in queryResults)
            {
                
                TwitterListView.DataSource = search.Statuses;
                TwitterListView.DataBind();
                //search.Entries[0].i
                //Author
                //Published
                

            }
        }


    }



    private static string LoadUrl(string url)
    {
        StreamReader sr = null;
        try
        {
            HttpWebRequest myRequest = (HttpWebRequest)(System.Net.WebRequest.Create(url));
            HttpWebResponse myResponse = (HttpWebResponse)(myRequest.GetResponse());
            sr = new System.IO.StreamReader(myResponse.GetResponseStream());
            return sr.ReadToEnd();
        }
        finally
        {
            if (sr != null)
            {
                sr.Dispose();
            }
        }
    }

    private void SetTheCorrectTabIndex()
    {
        if (SearchPhrase.ToLower().Contains("image") || SearchPhrase.ToLower().Contains("picture") || SearchPhrase.ToLower().Contains("photo"))
        {
            MainTabContainer.ActiveTabIndex = 1;
        }
        else if (SearchPhrase.ToLower().Contains("video") || SearchPhrase.ToLower().Contains("movie") || SearchPhrase.ToLower().Contains("trailer") || SearchPhrase.ToLower().Contains("episode") || SearchPhrase.ToLower().Contains("film"))
        {
            MainTabContainer.ActiveTabIndex = 3;
        }
        else if (GoogleNewsListView.Items.Count == 0)
        {
            MainTabContainer.ActiveTabIndex = 4;
            if (LiveSearchListView.Items.Count == 0)
            {
                MainTabContainer.ActiveTabIndex = 3;                
            }

        }
    }

    private void LoadFlickerImages()
    {
        //Photos photos = FlickrHelper.GetPhotosByKeyword(this.SearchPhrase);
        //FlickerImagesListView.DataSource = photos.PhotoCollection;
        //FlickerImagesListView.DataBind();
    }

    private void LoadPicasaImages()
    {
        AtomEntryCollection images = PicasaHelper.GetImagesByPhrase(this.SearchPhrase);
        PicasaImagesListView.DataSource = images;
        PicasaImagesListView.DataBind();
    }

    private void LoadVideos(string keyword)
    {
        try
        {
            string username = "seniordotnetdeveloper@gmail.com";
            string password = "dessi77&";
            string application = "buzzhour";
            string clientID = "ytapi-NikolayYordanov-buzzhour-673umn97-1";
            string developerKey = "AI39si65gkXT57qFsN8zVZiAMVRpySX9h_TVRKBS5F3bGrO0c06YuF6ISMhX2BQZyZp2MxMa_JOtcftvSeiA1kqIpzN2CulfYA";

            YouTubeService service = new YouTubeService(application, clientID, developerKey);
            service.setUserCredentials(username, password);

            YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
            query.Query = keyword;
            query.NumberToRetrieve = 18;
            YouTubeFeed videoFeed = service.Query(query);
            VideosListView.DataSource = videoFeed.Entries;
            VideosListView.DataBind();
            if (videoFeed.Entries.Count > 0)
            {
                VideosListView.SelectedIndex = 0;
                VideosListView_SelectedIndexChanged(VideosListView, new EventArgs());
            }
        }
        catch (Exception)
        {

        }

    }


    protected void VideosListView_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (VideosListView.Items[VideosListView.SelectedIndex].ItemType == ListViewItemType.DataItem)
        {

            ListViewDataItem data = VideosListView.Items[VideosListView.SelectedIndex] as ListViewDataItem;
            ImageButton VideoThumbNail = VideosListView.Items[VideosListView.SelectedIndex].FindControl("VideoThumbNail") as ImageButton;
            VideoPlayerSource.Text = ComplexStrings.YouTubePlayerNormalSize.Replace("MovieId", VideoThumbNail.DescriptionUrl);

            Label videoTitle = VideosListView.Items[VideosListView.SelectedIndex].FindControl("VideoTitle") as Label;
            VideoTitleLabel.Text = videoTitle.Text;


        }

    }

    protected void PicasaImagesListView_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem dataItem = e.Item as ListViewDataItem;
            PicasaEntry picasaImage = dataItem.DataItem as PicasaEntry;
            Image ImageThumbNail = e.Item.FindControl("ImageThumbNail") as Image;
            ImageThumbNail.ImageUrl = picasaImage.Media.Thumbnails[2].Url;
            ImageThumbNail.Attributes.Add("onclick", string.Format("window.open('{0}',null,'width=650','height=350','status=yes,toolbar=no,menubar=no,location=no,resizable=yes')", ImageThumbNail.ImageUrl.Replace("s288", "s800")));
            Label ImageTitle = e.Item.FindControl("ImageTitle") as Label;
            ImageTitle.Text = picasaImage.Summary.Text;

        }
    }

    protected void VideosListView_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem data = e.Item as ListViewDataItem;
            YouTubeEntry entry = data.DataItem as YouTubeEntry;
            ImageButton VideoThumbNail = e.Item.FindControl("VideoThumbNail") as ImageButton;
            Label VideoTitle = e.Item.FindControl("VideoTitle") as Label;
            VideoTitle.Text = entry.Title.Text;
            VideoThumbNail.ImageUrl = entry.Media.Thumbnails[0].Url;
            try
            {
                VideoThumbNail.DescriptionUrl = entry.Media.VideoId.Value;
            }
            catch (Exception)
            {

            }


        }
    }

    protected void VideosListView_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
    {
        if (VideosListView.Items[VideosListView.SelectedIndex].ItemType == ListViewItemType.DataItem)
        {
            VideosListView.SelectedIndex = e.NewSelectedIndex;

            e.Cancel = false;

        }
    }


    protected void FlickerImagesListView_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem dataItem = e.Item as ListViewDataItem;
            Photo flickrImage = dataItem.DataItem as Photo;
            Image ImageThumbNail = e.Item.FindControl("ImageThumbNail") as Image;
            ImageThumbNail.ImageUrl = flickrImage.SmallUrl;
            ImageThumbNail.Attributes.Add("onclick", string.Format("window.open('{0}',null,'width=650','height=350','status=yes,toolbar=no,menubar=no,location=no,resizable=yes')", flickrImage.MediumUrl));
            Label ImageTitle = e.Item.FindControl("ImageTitle") as Label;
            ImageTitle.Text = flickrImage.Title;

        }
    }

    protected void ActiveTabChanged(object sender, EventArgs e)
    {
        if (MainTabContainer.ActiveTabIndex == 1)
        {
            LoadFlickerImages();
        }
        if (MainTabContainer.ActiveTabIndex == 2)
        {
            LoadPicasaImages();
        }
    }

    protected void GoToVideosTabImageButton_Click(object sender, ImageClickEventArgs e)
    {
        this.MainTabContainer.ActiveTabIndex = 3;
    }
    protected void Label4_Click(object sender, EventArgs e)
    {
        this.MainTabContainer.ActiveTabIndex = 1;
        ActiveTabChanged(sender, e);
    }
    protected void ImagesLabel_Click(object sender, EventArgs e)
    {
        this.MainTabContainer.ActiveTabIndex = 2;
        ActiveTabChanged(sender, e);
    }
}

